<!--
 * @Author: guo-bomin 2974463764@qq.com
 * @Date: 2024-02-28 09:06:43
 * @LastEditors: guo-bomin 2974463764@qq.com
 * @LastEditTime: 2024-02-28 10:18:23
 * @FilePath: \my-vue-app\src\components\Tree\treeItem.vue
 * @Description: 郭博民16670506200
 * 有问题微信同号询问，急事call我
 * Copyright (c) 2024 by 湖南習羽网络科技有限公司, All Rights Reserved. 
-->
<template>
  <div class="treeNodeItem">
    <div class="iconAndName" tabindex="-1" @click="clickTree">
      <!-- <i class="el-icon-caret-right"></i> -->
      <el-icon
        v-if="props.item.children"
        @click.stop="clickIconFold"
        :class="['treeNodeItemIcon', isFold ? 'iconLeft' : 'iconDown']"
      >
        <ArrowRight />
      </el-icon>
      <!-- 右箭头图标 -->
      <span>{{ props.item.label }}</span>
    </div>
    <div
      class="childrenTreeNode"
      :style="{
        display: isFold ? 'none' : 'block',
      }"
    >
      <!-- 存在子节点就遍历并递归调用自身这个组件 -->
      <template v-if="props.item.children">
        <tree-item
          v-for="(ite, ind) in props.item.children"
          :key="ind"
          :item="ite"
          :expandTree="props.expandTree"
          :click-name-close="props.clickNameClose"
          v-bind="$attrs"
          v-on="$listeners"
        ></tree-item>
      </template>
    </div>
  </div>
</template>

<script setup>
import { defineComponent, watch } from 'vue';
const { proxy } = getCurrentInstance();
const isFold = ref(true); // 默认有子节点都折叠起来

defineEmits(['clickTree']);
const props = defineProps({
  item: {
    type: Object,
    required: true,
  },
  expandTree: {
    type: Boolean,
  },
  clickNameClose: {
    type: Boolean,
  },
});

watch(
  props.expandTree,
  (newVal) => {
    isFold.value = !newVal;
  },
  {
    immediate: true,
  }
);

function clickIconFold() {
  isFold.value = !isFold.value;
  console.log(`isFold.value -->`, isFold.value);
  proxy.$emit('fold', props.item, isFold.value ? '折叠咯' : '展开啦');
}
function clickTree() {
  // 默认是点击小图标才能关闭，加上clickNameClose为true属性，设置点击树节点name也能关闭
  if (props.clickNameClose) {
    clickIconFold();
  }
  proxy.$emit('clickTree', props.item);
}
</script>

<style lang="scss" scoped>
.treeNodeItem {
  width: 100%;
  height: auto;
  // 通过css解决树结构缩进问题，且要搭配.my-tree-wrap > .treeNodeItem { padding: 0; } (子元素选择器，并非后代元素选择器)
  padding-left: 12px;
  .iconAndName {
    width: 100%;
    height: 24px;
    display: flex;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s;
    box-sizing: border-box;
    .treeNodeItemIcon {
      margin-right: 4px;
    }
    // 点击图标旋转一下
    .iconDown {
      transform: rotate(90deg);
      transition: all 0.3s;
    }
    .iconLeft {
      transition: all 0.3s;
    }
    .treeNodeItemName {
      color: #666;
      word-break: keep-all; // 不换行
    }
    // 位置对齐一下
    .noChildrenIcon {
      margin-left: 20px;
    }
  }
  .iconAndName:hover {
    background-color: #f5f7fa;
  }
  // 搭配tabindex='-1'设置选中聚焦时的背景色
  .iconAndName:focus {
    background-color: #f5f7fa;
  }
}
</style>
